module.exports = init

/**
 * A way to communicate between players and rooms
 * @type {Room}
 */

var Room = require('../../models/room')

var roomManager = null
var roomPool //房间池
var activeRoomCount

function init() {
    if (roomManager)
        return roomManager

    //Do some works

    //Init room manager
    roomManager = {
        createRoom,
        enterRoom,
        closeRoom,
        exitRoom,
    }
    //Init room pool
    roomPool = new Array(100)
    activeRoomCount = 0

    return roomManager
}

/**
 * @param people 需要有id参数
 * @param peopleNum 房间人数
 * @returns {*}
 */
function createRoom(people, peopleNum) {
    console.log(people.id + '创建了一个多人房间: ' + peopleNum)

    //首先不做检查，返回一个指定人数的新房间，只有一个人
    var aRoom

    //Get a free room
    for (var i = 0; i < roomPool.length; i++) {
        if (roomPool[i] != null)
            continue

        roomPool[i] = new Room(peopleNum, roomManager)
        aRoom = roomPool[i]
        aRoom.roomNum = i
        aRoom.enter(people)
        break
    }

    if (aRoom) {
        activeRoomCount++
        console.log('Created room: ' + aRoom.roomNum + 'Now active room count: ' + activeRoomCount)
    }

    return aRoom
}

function enterRoom(people, roomNum) {
    var room = roomPool[roomNum]

    if (!room)
        return null


    if (room.enter(people)) {
        console.log('People:' + people.id + ' entered room ' + roomNum)
        return room
    }else{
        return null
    }
}


function closeRoom(roomNum) {
    roomPool[roomNum] = undefined
    activeRoomCount--
    console.log('Close room: ' + roomNum + ' now active room count: ' + activeRoomCount)
}

function exitRoom(roomNum, sid) {
    if (roomPool[roomNum]) {
        roomPool[roomNum].exit(sid)
        console.log('People:' + sid + ' exited room: ' + roomNum)
    }
}